#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
加密货币爆仓数据监控系统 - 主入口
"""

import asyncio
import uvicorn
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from loguru import logger

from websocket_client import CoinankWebSocketClient
from data_processor import LiquidationDataProcessor
from api_routes import router, set_data_processor

# 创建FastAPI应用
app = FastAPI(
    title="加密货币爆仓数据监控API",
    description="实时监控和统计加密货币爆仓数据",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 全局数据处理器实例
data_processor = LiquidationDataProcessor()
websocket_client = None

# 静态文件目录配置
static_dir = Path(__file__).parent / "static"

@app.on_event("startup")
async def startup_event():
    """应用启动时的初始化"""
    global websocket_client
    logger.info("启动爆仓数据监控系统...")
    
    # 检查静态文件目录
    if not static_dir.exists():
        logger.warning(f"静态文件目录不存在: {static_dir}")
        logger.info("请先在前端目录运行 'npm run build' 构建前端应用")
    else:
        logger.info(f"静态文件目录已找到: {static_dir}")
        
        # 配置静态文件服务 - 挂载到根路径
        app.mount("/", StaticFiles(directory=str(static_dir), html=True), name="static")
        logger.info(f"静态文件目录已挂载: {static_dir}")
    
    # 启动数据处理器的后台任务（清理+定期重算）
    await data_processor.start_background_tasks()
    
    # 设置API路由的数据处理器引用
    set_data_processor(data_processor)
    
    # 创建WebSocket客户端
    websocket_client = CoinankWebSocketClient(data_processor)
    
    # 启动WebSocket连接
    asyncio.create_task(websocket_client.start())
    
    logger.info("系统启动完成")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭时的清理"""
    logger.info("关闭爆仓数据监控系统...")
    
    # 停止数据处理器的后台任务
    await data_processor.stop_background_tasks()
    
    if websocket_client:
        await websocket_client.stop()
    logger.info("系统已关闭")

# 健康检查端点
@app.get("/health")
async def health_check():
    return {
        "status": "healthy",
        "websocket_connected": websocket_client.is_connected() if websocket_client else False,
        "data_count": data_processor.get_total_records_count(),
        "frontend_available": static_dir.exists()
    }

# 注册API路由
app.include_router(router, prefix="/api")

# 根路径 - 返回 index.html
@app.get("/")
async def root():
    """根路径返回前端应用"""
    index_html = static_dir / "index.html"
    if index_html.exists():
        return FileResponse(str(index_html))
    else:
        return JSONResponse({
            "message": "Crypto Liquidation Monitor API is running",
            "frontend_status": "not_built",
            "instruction": "Please run 'npm run build' in the frontend directory"
        })

# SPA路由处理 - 捕获所有其他路径并返回index.html
@app.get("/{path:path}")
async def catch_all(path: str):
    """捕获所有路径用于SPA路由"""
    # 检查是否是静态文件请求
    if path.startswith("assets/") or path.endswith((".js", ".css", ".png", ".jpg", ".svg")):
        file_path = static_dir / path
        if file_path.exists() and file_path.is_file():
            return FileResponse(str(file_path))
    
    # 否则返回index.html用于SPA路由
    index_html = static_dir / "index.html"
    if index_html.exists():
        return FileResponse(str(index_html))
    else:
        return JSONResponse({"error": "Frontend not built"}, status_code=404)

if __name__ == "__main__":
    # 配置日志
    logger.add("logs/app.log", rotation="1 day", retention="7 days")
    
    # 启动服务器
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=False,  # 生产环境关闭热重载
        log_level="info"
    )